package com.fyl.web;

import com.fyl.WebApplicationContextUtils;
import com.fyl.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/accountServlet")
public class AccountServlet extends HttpServlet {
//    @Override
//    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        //web层调用service层，获得accountService,accountService存在于applicationContext中
//        //ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext2.xml");
//        ServletContext servletContext = req.getServletContext();
//        ApplicationContext context = (ApplicationContext) servletContext.getAttribute("applicationContext");
//        AccountService accountService = context.getBean(AccountService.class);
//        accountService.transferMoney("tom","lucy",500);
//    }

    //去除硬编码
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //web层调用service层，获得accountService,accountService存在于applicationContext中
        //ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext2.xml");
        ServletContext servletContext = req.getServletContext();
//        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContextByServletContext(servletContext);
        ApplicationContext context =org.springframework.web.context.support.WebApplicationContextUtils.getWebApplicationContext(servletContext);
        AccountService accountService = context.getBean(AccountService.class);
        accountService.transferMoney("tom","lucy",500);
    }
}
